<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Music/classes/PhpFox_ServiceMusic.class.php, $Author:  $ */



/** Service for working with music
 *
 * @package module.music
 * @version $Id: PhpFox_ServiceMusic.class.php 416 2008-03-28 07:20:51Z phpfoxsv $
 *
 */
class PhpFox_Mod_Music_ServiceMusic extends BaseService
{
    function onDeleteAccount($aParams)
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oAlbumItem = &$this->_oModule->getItem('Album');
        /* @var $oSongItem PhpFox_Mod_Music_ItemAlbum */
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */
        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */

        $aIds = $aParams['aIds'];
        foreach ($aIds as $iUserId)
        {
            $aCond = array
            (
                'user_id'  => '= '.$iUserId,
                'album_id' => '= 0',
            );
            list($aSongs) = $oSongItem->getList($aCond);
            foreach ($aSongs as $aSong)
            {
                $sSql = 'DELETE FROM '.App::getT('music_favorite').' '.
                       ' WHERE song_id = '.$aSong['song_id'];
                $oFavoriteItem->oDb->query($sSql);
                $this->deleteSong($aSong['song_id']);
                $oSongItem->oDb->query('UPDATE '.App::getT('user').' '.
                                      ' SET actual_song_id = 0 '.
                                      ' WHERE actual_song_id = '.$aSong['song_id']);
            }

            $aCond = array
            (
                'user_id' => '= '.$iUserId,
            );
            list($aAlbums) = $oAlbumItem->getList($aCond);
            foreach ($aAlbums as $aAlbum)
            {
                $sSql = 'DELETE FROM '.App::getT('music_favorite').' '.
                       ' WHERE album_id = '.$aAlbum['album_id'];
                $oFavoriteItem->oDb->query($sSql);
                $this->deleteAlbum($aAlbum['album_id']);
            }

            $sSql = 'DELETE FROM '.App::getT('music_favorite').' '.
                   ' WHERE user_id = '.$iUserId;
            $oFavoriteItem->oDb->query($sSql);
        }
        return true;
    }

    /** Deleting favorite item (song or album)
     *
     * @param integer $iFavoriteId
     * @return boolean
     */
    function deleteFavorite($iFavoriteId)
    {
        $iFavoriteId = intval($iFavoriteId);
        if (!$iFavoriteId)
        {
            return false;
        }

        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */

        if ($oFavoriteItem->delete($iFavoriteId))
        {
            return true;
        }
        return false;
    }

    /** Getting favorite song list
     *
     * @param string $sUser
     * @return array
     */
    function getFavoriteSongs($sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */

        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!$oUser)
        {
            return array();
        }

        $sSql = 'SELECT mf.favorite_id AS favorite_id, mf.user_id AS user_id, ms.song_id AS song_id, ms.song_title AS song_title, mm.musician_id AS musician_id, mm.musician_name AS musician_name  '.
               ' FROM '.App::getT('music_favorite').' AS mf '.
               ' LEFT JOIN '.App::getT('music_song').' AS ms USING(song_id) '.
               ' LEFT JOIN '.App::getT('music_musician').' AS mm USING(musician_id) '.
               ' WHERE mf.user_id = '.$oUser->aData['id'].' '.
               '   AND mf.album_id = 0 '.
               ' ORDER BY ms.song_title';
        return $oFavoriteItem->oDb->getRows($sSql);
    }

    /** Getting favorite albums list
     *
     * @param string $sUser
     * @return array
     */
    function getFavoriteAlbums($sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */

        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!$oUser)
        {
            return array();
        }

        $sSql = 'SELECT mf.favorite_id AS favorite_id, ma.album_id AS album_id, ma.album_title AS album_title, mm.musician_name AS musician_name, mm.musician_id AS musician_id  '.
               ' FROM '.App::getT('music_favorite').' AS mf '.
               ' LEFT JOIN '.App::getT('music_album').' AS ma USING(album_id) '.
               ' LEFT JOIN '.App::getT('music_musician').' AS mm USING(musician_id) '.
               ' WHERE mf.user_id = '.$oUser->aData['id'].' '.
               '   AND mf.song_id = 0 '.
               ' ORDER BY ma.album_title';
        return $oFavoriteItem->oDb->getRows($sSql);
    }

    /** Get featured songs list
     *
     * @param integer $iLimit
     * @return array
     */
    function getFeaturedSongs($iLimit)
    {
        $aCond = array
        (
            'song_is_approved' => '= 1',
            'song_is_featured' => '= 1',
        );
        $sSort = 'RAND()';
        list($aSongs) = $this->getSongsList($aCond, 1, $iLimit, $sSort);
        return $aSongs;
    }

    /** Get featured musicians list
     *
     * @param integer $iLimit
     * @return array
     */
    function getFeaturedMusicians($iLimit)
    {
        $oMusicianItem = &$this->_oModule->getItem('Musician');
        /* @var $oMusicianItem PhpFox_Mod_Music_ItemMusician */

        $aCond = array
        (
            'musician_is_featured' => '= 1',
        );
        $sSort = 'RAND()';
        list($aMusicians) = $oMusicianItem->getList($aCond, 1, $iLimit, $sSort);
        return $aMusicians;
    }

    /** Set album status to favorite
     *
     * @param integer $iAlbumId
     * @param string $sUser
     * @return boolean
     */
    function makeAlbumFavorite($iAlbumId, $sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */
        $oAlbumItem = &$this->_oModule->getItem('Album');
        /* @var $oSongItem PhpFox_Mod_Music_ItemAlbum */

        $iAlbumId = intval($iAlbumId);
        if (!$iAlbumId)
        {
            return false;
        }
        if (!$oAlbumItem->load($iAlbumId))
        {
            return false;
        }
        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!$oUser)
        {
            return false;
        }
        if (!$oFavoriteItem->loadByCondition('mf.album_id = '.$iAlbumId.' AND mf.user_id = '.$oUser->aData['id']))
        {
            $oFavoriteItem->aData['album_id'] = $iAlbumId;
            $oFavoriteItem->aData['user_id'] = $oUser->aData['id'];
            $oFavoriteItem->insert();
        }
        return true;
    }

    /** Set song status to favorite
     *
     * @param integer $iSongId
     * @param string $sUser
     * @return boolean
     */
    function makeSongFavorite($iSongId, $sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */

        $iSongId = intval($iSongId);
        if (!$iSongId)
        {
            return false;
        }
        if (!$oSongItem->load($iSongId))
        {
            return false;
        }
        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!$oUser)
        {
            return false;
        }
        if (!$oFavoriteItem->loadByCondition('mf.song_id = '.$iSongId.' AND mf.user_id = '.$oUser->aData['id']))
        {
            $oFavoriteItem->aData['song_id'] = $iSongId;
            $oFavoriteItem->aData['user_id'] = $oUser->aData['id'];
            $oFavoriteItem->insert();
        }
        return true;
    }

    /** Check that song is favorite
     *
     * @param integer $iSongId
     * @param string $sUser
     * @return boolean
     */
    function isSongFavorite($iSongId, $sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */

        $iSongId = intval($iSongId);
        if (!$iSongId)
        {
            return false;
        }
        if (!$oSongItem->load($iSongId))
        {
            return false;
        }
        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!isset($oUser->aData['id']))
        {
            return false;
        }
        if (!$oFavoriteItem->loadByCondition('mf.song_id = '.$iSongId.' AND mf.user_id = '.$oUser->aData['id']))
        {
            return false;
        }
        return true;
    }

    /** Check that album is favorite
     *
     * @param integer $iAlbumId
     * @param string $sUser
     * @return boolean
     */
    function isAlbumFavorite($iAlbumId, $sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oFavoriteItem = &$this->_oModule->getItem('Favorite');
        /* @var $oFavoriteItem PhpFox_Mod_Music_ItemFavorite */
        $oAlbumItem = &$this->_oModule->getItem('Album');
        /* @var $oSongItem PhpFox_Mod_Music_ItemAlbum */

        $iAlbumId = intval($iAlbumId);
        if (!$iAlbumId)
        {
            return false;
        }
        if (!$oAlbumItem->load($iAlbumId))
        {
            return false;
        }
        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!isset($oUser->aData['id']))
        {
            return false;
        }
        if (!$oFavoriteItem->loadByCondition('mf.album_id = '.$iAlbumId.' AND mf.user_id = '.$oUser->aData['id']))
        {
            return false;
        }
        return true;
    }

    /** Calculating song obtained space
     *
     * @param string $sUser
     * @return integer
     */
    function calcObtainedSpace($sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */
        $oAlbumItem = &$this->_oModule->getItem('Album');
        /* @var $oSongItem PhpFox_Mod_Music_ItemAlbum */

        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!isset($oUser->aData['id']))
        {
            return false;
        }

        $aCond = array
        (
            'user_id' => '= '.$oUser->aData['id'],
        );
        $iSpace = 0;
        $sDestPath = App::getParam('music.path');
        $sAlbumPath = App::getParam('music.album.pic.path');

        list($aSongs) = $oSongItem->getList($aCond);
        foreach ($aSongs as $aSong)
        {
            if (file_exists($sDestPath.$aSong['song_id'].'.mp3'))
            {
                $iSpace += filesize($sDestPath.$aSong['song_id'].'.mp3');
            }
        }

        list($aAlbums) = $oAlbumItem->getList($aCond);
        foreach ($aAlbums as $aAlbum)
        {
            if (file_exists($sAlbumPath.$aAlbum['album_id'].'.jpg'))
            {
                $iSpace += filesize($sAlbumPath.$aAlbum['album_id'].'.jpg');
            }
        }

        return $iSpace;
    }

    /** Returns top requested songs
     *
     * @param integer $iLimit
     * @return array
     */
    function getTopRequestedSongs($iLimit)
    {
        $aCond = array
        (
            'song_is_approved' => '= 1',
            'song_play'        => '> 0',
        );

        list($aSongs) = $this->getSongsList($aCond, 1, $iLimit, $sSort = 'song_play DESC');
        return $aSongs;
    }

    /** Getting songs list with the full song info
     *
     * @param array $aCond
     * @param integer $iPage
     * @param integer $iPageSize
     * @param string $sSort
     * @param array $aFields
     * @return array
     */
    function getSongsList($aCond = array(), $iPage = 0, $iPageSize = 0, $sSort = '', $aFields = array())
    {
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */

        $aMap = array
        (
            'musician_name'        => 'mm.musician_name',
            'musician_is_featured' => 'mm.musician_is_featured',
            'genre_name'           => 'mg.genre_name',            // GloGen Added
            'user_name'            => 'u.user',                   // GloGen added
            'album_title'          => 'ma.album_title',
        );
        $aMap = array_merge($aMap, $oSongItem->aFields);
        $sCond = $oSongItem->_parseCond($aCond, $aMap);
        $sSql = 'SELECT COUNT(*) '.
               ' FROM `'.$oSongItem->sTable.'` AS '.$oSongItem->sAlias.
               ' WHERE '.$sCond;
        $iCnt = $oSongItem->oDb->getField($sSql);
        $aRows = array();
        if ($iCnt)
        {
            $sSort = ($sSort ? $sSort : 'song_id');
            $iOffset = $oSongItem->_getOffset($iPage, $iPageSize, $iCnt);
            $sSql = 'SELECT '.$oSongItem->_joinFields($aMap, $aFields).
                    ' FROM `'.$oSongItem->sTable.'` AS '.$oSongItem->sAlias.
                    ' LEFT JOIN `'.App::getT('music_musician').'` AS mm USING(musician_id) '.
                    ' LEFT JOIN `'.App::getT('music_genre').'` AS mg ON '.$oSongItem->sAlias.'.genre_id = mg.genre_id '.  // GloGen Added
                    ' LEFT JOIN `'.App::getT('user').'` AS u ON '.$oSongItem->sAlias.'.user_id = u.id '.                  // GloGen Added
                    ' LEFT JOIN `'.App::getT('music_album').'` AS ma ON ( ' . $oSongItem->sAlias . '.album_id = ma.album_id) ' .
                    ' WHERE '.$sCond.
                    ($sSort?(' ORDER BY '.$sSort):'').
                    ($iPageSize?(' LIMIT '.$iOffset.','.$iPageSize):'');
            $aRows = $oSongItem->oDb->getRows($sSql, true);
        }
        return array($aRows, $iCnt);
    }

/** Set album status approved.
 *
 * @param integer $iId : album id
 * @return boolean : true - on success, false elsewhere
 */
    function setAlbumApproved($iId=0){
        $oAlbumItem = &$this->_oModule->getItem('Album');

        if ($oAlbumItem->load($iId)){
            $oAlbumItem->aData['album_is_approved'] = 1;
            if ($oAlbumItem->update(array('album_is_approved'))){
//Also approving album songs
                $aCond  = array('album_id'         => '='.$iId,
                                'song_is_approved' => '='.'0',);
                list($aSongs,$iCnt) = $this->getSongsList($aCond);
                foreach($aSongs as $val){
                    $iSongId = intval($val['song_id']);
                    $this->setSongApproved($iSongId);
                }
            }else{
                $this->addErrors($oAlbumItem->getErrors());
                return false;
            }
        }else{
            $this->addErrors($oAlbumItem->getErrors());
            return false;
        }
        return true;
    }

/** Delete album.
 *
 * @param integer $iId : album id
 * @return boolean : true - on succes, false - elsewhere
 */
    function deleteAlbum($iId=0){
        $oAlbumItem = &$this->_oModule->getItem('Album');

        if ($oAlbumItem->load($iId)){
            if ($oAlbumItem->delete($iId)){
                $aSongs = $this->getSongNames(array('album_id' => '= '.$iId));
                $oCommentService = &App::getModuleService('Comments', 'Comment');
        		/* @var $oCommentService PhpFox_Mod_Comments_ServiceComment */
        		$oCommentService->onItemDelete($iId, 'music_album');
                foreach($aSongs as $val){
                    $this->deleteSong($val['song_id']);
                }
                $oAccountService = &App::getModuleService('Account', 'Account');
        		/* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
                $oAccountService->changeUserInfo($oAccountService->getById($oAlbumItem->aData['user_id']), 'music', -1);
            }else{
                $this->addErrors($oAlbumItem->getErrors());
                return false;
            }
        }else{
            $this->addErrors($oAlbumItem->getErrors());
            return false;
        }
        $this->checkMusician($oAlbumItem->aData['musician_id']);
        $sSql = 'DELETE FROM '.App::getT('music_favorite').' '.
               ' WHERE album_id = '.$iId;
        $oAlbumItem->oDb->query($sSql);
        $sAlbumPic = App::getParam('music.album.pic.path').$iId.'.jpg';
        if (file_exists($sAlbumPic))
        {
            unlink($sAlbumPic);
        }
        return true;
    }

    /** Increment song plays counter
     *
     * @param integer $iSongId
     * @return boolean
     */
    function makeSongPlayed($iSongId)
    {
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */

        $iSongId = intval($iSongId);
        if ($oSongItem->load($iSongId))
        {
            $oSongItem->aData['song_play']++;
            $oSongItem->update(array('song_play'));
            return true;
        }
        return false;
    }

/** Set song status approved.
 *
 * @param integer $iId : song id
 * @return boolean : true - on success, flase - elseware
 */
    function setSongApproved($iId=0){
        $oSongItem = &$this->_oModule->getItem('Song');

        if ($oSongItem->load($iId)){
            $oSongItem->aData['song_is_approved'] = 1;
            if ($oSongItem->update(array('song_is_approved'))){
            }else{
                $this->addErrors($oSongItem->getErrors());
                return false;
            }
        }else{
            $this->addErrors($oSongItem->getErrors());
            return false;
        }
        return true;
    }
/** Set song status to featured or not featured.
 *
 * @param integer $iId		: song id
 * @param boolean $featured : status, true - featured, false - not featured
 * @return true - on success, false elsewhere
 */
    function setSongFeaturedState($iId=0, $featured=true){
        $oSongItem = &$this->_oModule->getItem('Song');

        if ($oSongItem->load($iId)){
            if ($featured){
                $oSongItem->aData['song_is_featured'] = 1;
            }else{
                $oSongItem->aData['song_is_featured'] = 0;
            }
            if ($oSongItem->update(array('song_is_featured')) ){
            }else{
                $this->addErrors($oSongItem->getErrors());
                return false;
            }
        }else{
            $this->addErrors($oSongItem->getErrors());
            return false;
        }
        return true;
    }

    /** Generating xml config file for mp3 flash player
     *
     * @param array $aData params
     * @return string
     */
    function genConfigXML($aData = array())
    {
        $aConfigData = array
        (
            'autostart'    => isset($aData['autostart']) ? $aData['autostart'] : 'false',
            'shuffle'      => isset($aData['shuffle']) ? $aData['shuffle'] : 'false',
            'repeat'       => isset($aData['repeat']) ? $aData['repeat'] : 'list',
            'volume'       => isset($aData['volume']) ? $aData['volume'] : '30',
            'showdisplay'  => isset($aData['showdisplay']) ? $aData['showdisplay'] : 'true',
            'showplaylist' => isset($aData['showplaylist']) ? $aData['showplaylist'] : 'true',
            'linktarget'   => isset($aData['linktarget']) ? $aData['linktarget'] : '_top',
            'backcolor'    => isset($aData['backcolor']) ? $aData['backcolor'] : '0xffffff',
            'frontcolor'   => isset($aData['frontcolor']) ? $aData['frontcolor'] : '0x333333',
            'lightcolor'   => isset($aData['lightcolor']) ? $aData['lightcolor'] : '0x000000',
            'jpgfile'      => isset($aData['jpgfile']) ? $aData['jpgfile'] : '',
            'callback'     => isset($aData['callback']) ? $aData['callback'] : '',
        );
        $sData = '';
        $sData .= "<mp3config>\n";
        $sData .= "<autostart>".$aConfigData['autostart']."</autostart>\n";
        $sData .= "<shuffle>".$aConfigData['shuffle']."</shuffle>\n";
        $sData .= "<repeat>".$aConfigData['repeat']."</repeat>\n";
        $sData .= "<volume>".$aConfigData['volume']."</volume>\n";
        $sData .= "<showdisplay>".$aConfigData['showdisplay']."</showdisplay>\n";
        $sData .= "<showplaylist>".$aConfigData['showplaylist']."</showplaylist>\n";
        $sData .= "<linktarget>".$aConfigData['linktarget']."</linktarget>\n";
        $sData .= "<backcolor>".$aConfigData['backcolor']."</backcolor>\n";
        $sData .= "<frontcolor>".$aConfigData['frontcolor']."</frontcolor>\n";
        $sData .= "<lightcolor>".$aConfigData['lightcolor']."</lightcolor>\n";
        $sData .= "<jpgfile>".$aConfigData['jpgfile']."</jpgfile>\n";
        $sData .= "<callback>".$aConfigData['callback']."</callback>\n";
        $sData .= "</mp3config>\n";
        return $sData;
    }

    /** Generate xml playlist for player
     *
     * @param mixed $mSongs
     * @return string
     */
    function genPlaylistXML($mSongs)
    {
        if (!is_array($mSongs))
        {
            $mSongs = explode(',', $mSongs);
        }
        foreach ($mSongs as $iKey => $iSong)
        {
            $mSongs[$iKey] = intval($iSong);
        }
        $sIn = implode(', ', $mSongs);
        $aCond = array
        (
            'song_id' => ' IN ('.$sIn.')',
        );
        list($aSongs) = $this->getSongsList($aCond);
        if (!count($aSongs))
        {
            return '';
        }

		return '';
    }

    /** Get full song content
     *
     * @param integer $iSongId
     * @return string
     */
    function getSongData($iSongId)
    {
        $iSongId = intval($iSongId);
        $sMusicFile = App::getParam('music.path').$iSongId.'.mp3';

        if (!file_exists($sMusicFile))
        {
            return '';
        }

		header("Content-Type: audio/mpeg");
		return file_get_contents($sMusicFile);
    }

    /** Set musician feature status
     *
     * @param integer $iMusicianId
     * @param boolean $bFeatured
     * @return boolean
     */
    function setMusicianFeatureState($iMusicianId, $bFeatured = true)
    {
        $oMusicianItem = &$this->_oModule->getItem('Musician');
        /* @var $oMusucianItem PhpFox_Mod_Music_ItemMusician */

        if ($oMusicianItem->load($iMusicianId))
        {
            $oMusicianItem->aData['musician_is_featured'] = $bFeatured ? 1 : 0;
            $oMusicianItem->update(array('musician_is_featured'));
            return true;
        }
        return false;
    }

/** Delete song with 'song_id' = $Id
 *
 * @param integer $iId	: song id
 * @param $bCheckDelete Check deletion of artist and albums
 * @return boolean : true - on success, false - elsewhere
 */
    function deleteSong($iId=0, $bCheckDelete = true)
    {
        $oSongItem = &$this->_oModule->getItem('Song');

        if ($oSongItem->load($iId)){
            if (!$oSongItem->delete($iId)){
                $this->addErrors($oSongItem->getErrors());
                return false;
            }
            	$oAccountService = &App::getModuleService('Account', 'Account');
        		/* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
                $oCommentService = &App::getModuleService('Comments', 'Comment');
        		/* @var $oCommentService PhpFox_Mod_Comments_ServiceComment */
        		$oCommentService->onItemDelete($iId, 'music_song');
                $oAccountService->changeUserInfo($oAccountService->getById($oSongItem->aData['user_id']), 'music', -1);
        }else{
            $this->addErrors($oSongItem->getErrors());
            return false;
        }
        if ($bCheckDelete)
        {
            $this->checkAlbum($oSongItem->aData['album_id']);
            $this->checkMusician($oSongItem->aData['musician_id']);
        }
        $sSql = 'DELETE FROM '.App::getT('music_favorite').' '.
               ' WHERE song_id = '.$iId;
        $oSongItem->oDb->query($sSql);
        $sSql = 'UPDATE '.App::getT('user').' '.
               ' SET actual_song_id = "" '.
               ' WHERE actual_song_id = '.$iId;
        $oSongItem->oDb->query($sSql);
        $sSongPath = App::getParam('music.path').$iId.'.mp3';
        if (file_exists($sSongPath))
        {
            unlink($sSongPath);
        }
        return true;
    }

/** Get albums with status 'approved' = 0.
 *
 * @param array   $aCond	 : array of conditions
 * @param integer $iPage	 : page number
 * @param integer $iPageSize : page size
 * @param string  $sSort	 : MySQL fields and sort order
 * @param array   $aFields	 : array of fields
 * @return array(array(Albums), array(Count_of_record))
 */
    function getUnapprovedAlbums($aCond = array(), $iPage = 0, $iPageSize = 0, $sSort = '', $aFields = array()){
        $aCond = array
        (
            'album_is_approved' => '!= 1',
        );
        $aRes = $this->getAlbumsList($aCond, $iPage, $iPageSize, $sSort, $aFields);
        return $aRes;
    }

/** Get songs with status 'approved' = 0.
 *
 * @param array   $aCond	 : array of conditions
 * @param integer $iPage	 : page number
 * @param integer $iPageSize : page size
 * @param string  $sSort	 : MySQL fields and sort order
 * @param array   $aFields	 : array of fields
 * @return array(array(Songs), array(Count_of_record))
 */
    function getUnapprovedSongs($aCond = array(), $iPage = 0, $iPageSize = 0, $sSort = '', $aFields = array()){
        $aCond = array
        (
            'song_is_approved' => '!= 1',
        );
        $aRes = $this->getSongsList($aCond, $iPage, $iPageSize, $sSort, $aFields);
        return $aRes;
    }

/** Get list of albums
 *
 * @param array   $aCond	 : array of conditions
 * @param integer $iPage	 : page number
 * @param integer $iPageSize : page size
 * @param string  $sSort	 : MySQL fields and sort order
 * @param array   $aFields	 : array of fields
 * @return array (array(Albums_List), array(count_of_record))
 */
    function getAlbumsList($aCond = array(), $iPage = 0, $iPageSize = 0, $sSort = '', $aFields = array())
    {
        $oAlbumItem = &$this->_oModule->getItem('Album');
        /* @var $oSongItem PhpFox_Mod_Music_ItemAlbum */
        $oGenreItem = &$this->_oModule->getItem('Genre');

        $aMap = array
        (
            'musician_name'        => 'mm.musician_name',
            'musician_is_featured' => 'mm.musician_is_featured',
            'genre_name'           => 'mg.genre_name',
            'user_name'            => 'u.user',
        );
        $aMap = array_merge($aMap, $oAlbumItem->aFields);
        $sCond = $oAlbumItem->_parseCond($aCond, $aMap);
        $sSql = 'SELECT COUNT(*) '.
               ' FROM `'.$oAlbumItem->sTable.'` AS '.$oAlbumItem->sAlias.
               ' WHERE '.$sCond;
        $iCnt = $oAlbumItem->oDb->getField($sSql);
        $aRows = array();
        if ($iCnt)
        {
            $iOffset = $oAlbumItem->_getOffset($iPage, $iPageSize, $iCnt);
            $sSql = 'SELECT '.$oAlbumItem->_joinFields($aMap, $aFields).
                    ' FROM `'.$oAlbumItem->sTable.'` AS '.$oAlbumItem->sAlias.
                    ' LEFT JOIN `'.App::getT('music_musician').'` AS mm USING(musician_id) '.
                    ' LEFT JOIN `'.App::getT('music_genre').'` AS mg ON '.$oAlbumItem->sAlias.'.genre_id = '.$oGenreItem->sAlias.'.genre_id'.
                    ' LEFT JOIN `'.App::getT('user').'` AS u ON '.$oAlbumItem->sAlias.'.user_id = u.id'.
            //        ' LEFT JOIN `'.App::getT('music_song').'` AS ms ON ' . $oAlbumItem->sAlias.'.album_id = ms.album_id ' .
            //        ' WHERE '.$sCond . ' AND ms.song_id IS NOT NULL ' .
                    ' WHERE '.$sCond .
                    ($sSort?(' ORDER BY '.$sSort):'').
                    ($iPageSize?(' LIMIT '.$iOffset.','.$iPageSize):'');
            $aRows = $oAlbumItem->oDb->getRows($sSql, true);
        }
        return array($aRows, $iCnt);
    }

/** Get list of songs with some conditions.
 *
 * @param  array $aCond
 * @return array $aRows: array of Songs.
 */
    function getSongNames($aCond = array())
    {
        $oSongItem = &$this->_oModule->getItem('Song');

        $aMap = array();
        $aMap = array_merge($aMap, $oSongItem->aFields);

        $sCond = $oSongItem->_parseCond($aCond, $aMap);

        $sSql = 'SELECT '.$oSongItem->_joinFields($aMap).
                ' FROM `'.$oSongItem->sTable.'` AS '.$oSongItem->sAlias.
                ' WHERE '.$sCond;
        $aRows = $oSongItem->oDb->getRows($sSql, true);
        return $aRows;
    }

/** Save song details. Save album data.  Attention: 'album_id' is replaced 'album_name',
 * 										 Attention: 'musician_id' is replaced 'musician_name'
 *
 * @param unknown_type $iSongId
 * @param unknown_type $aSongData
 */
    function saveSong($iSongId=0,$aSongData=array())
    {
        $oSongItem = &$this->_oModule->getItem('Song');

        $iMusicianId = $this->addMusician($aSongData['musician_name']);

        $aSongData['musician_id'] = $iMusicianId;
        if ($oSongItem->load($iSongId)){
            $oSongItem->setData($aSongData);
            $oSongItem->update(array('song_title', 'musician_id', 'genre_id'));
        }
    }

/** Get hash of genres. Add unknown genre array('0' => 'Unknown')
 *
 * @return array $aRows: hash of genres,  ( 'genre_id' => 'genre_name')
 */
    function getGenres(){
        $oGenreItem = &$this->_oModule->getItem('Genre');

        $aGenres = array(0=>App::format('core.unkown'));
        $aRows = $oGenreItem->getHash('genre_name');
        foreach ($aRows as $k=>$v){
            $aGenres[$k] = App::formatTranslate($v);
        }
        return $aGenres;
    }

/** Save album data.  Attention: 'musician_id' is replaced 'musician_name'
 *
 * @param int $iAlbumId		: Album Id
 * @param array $aAlbumData : Data for album updating. Exeption: 'musician_id' is replaced 'musician_name'
 * @return bool				: true - Ok, false - error.
 */
    function saveAlbum( $iAlbumId=0, $aAlbumData=array() )
    {
        $oAlbumItem = &$this->_oModule->getItem('Album');

        $oMusicianItem = &$this->_oModule->getItem('Musician');

        $oAlbumItem->load($iAlbumId);
        $iMusicianId = $oAlbumItem->aData['musician_id'];
        $oMusicianItem->load($iMusicianId);

        if ($oMusicianItem->aData['musician_name'] != $aAlbumData['musician_name'])
        {
            /*$oMusicianItem->aData['musician_id']           = 0;
            $oMusicianItem->aData['musician_name']         = $aAlbumData['musician_name'];
            $oMusicianItem->aData['musician_is_featured']  = 0;
            $iMusicianId = $oMusicianItem->insert(true);
            if ( 0 == $iMusicianId )
            {
                $this->addErrors($oMusicianItem->getErrors());
                return false;
            }*/
            $iMusicianId = $this->addMusician($aAlbumData['musician_name']);
        }
        $oAlbumItem->aData['musician_id'] = $iMusicianId;
        $oAlbumItem->aData['genre_id'] = $aAlbumData['genre_id'];
        $oAlbumItem->aData['album_title'] = $aAlbumData['album_title'];
        $oAlbumItem->aData['album_description'] = (isset($aAlbumData['album_description']) ? $aAlbumData['album_description'] : '');
        $oAlbumItem->aData['album_year'] = $aAlbumData['album_year'];

        if (!$oAlbumItem->update())
        {
            $this->addErrors($oAlbumItem->getErrors());
            return false;
        }
        return true;
    }

    /** Adding musician to database, or returns musician_id if exists
     *
     * @param string $sMusicianName
     * @return integer
     */
    function addMusician($sMusicianName)
    {
        $oMusicianItem = &$this->_oModule->getItem('Musician');
        /* @var $oMusucianItem PhpFox_Mod_Music_ItemMusician */

        $sMusicianName = Database::escape($sMusicianName);
        if (!$oMusicianItem->loadByCondition('LOWER(musician_name) = "'.strtolower($sMusicianName).'"'))
        {
            $oMusicianItem->aData['musician_name'] = $sMusicianName;
            return $oMusicianItem->insert();
        }
        return $oMusicianItem->aData['musician_id'];
    }

    /** Check that musician is empty and delete it, if empty
     *
     * @param integer $iMusicianId
     * @return boolean
     */
    function checkMusician($iMusicianId)
    {
        $oMusicianItem = &$this->_oModule->getItem('Musician');
        /* @var $oMusucianItem PhpFox_Mod_Music_ItemMusician */

        $iMusicianId = intval($iMusicianId);
        if (!$iMusicianId)
        {
            return true;
        }
        $sSql = 'SELECT COUNT(*) '.
               ' FROM '.App::getT('music_song').' AS ms '.
               ' LEFT JOIN '.App::getT('music_album').' AS ma ON ma.musician_id = '.$iMusicianId.' '.
               ' WHERE ms.musician_id = '.$iMusicianId;
        $iItemsCount = $oMusicianItem->oDb->getField($sSql);
        if (!$iItemsCount)
        {
            $oMusicianItem->delete($iMusicianId);
            return false;
        }
        return true;
    }


    /** Check album by album_id, and delete it if empty
     *
     * @param integer $iAlbumId
     * @return boolean
     */
    function checkAlbum($iAlbumId)
    {
        $oAlbumItem = &$this->_oModule->getItem('Album');
        /* @var $oSongItem PhpFox_Mod_Music_ItemAlbum */

        $iAlbumId = intval($iAlbumId);
        if (!$iAlbumId)
        {
            return true;
        }
        // counting songs
        $sSql = 'SELECT COUNT(*) '.
               ' FROM '.App::getT('music_song').' '.
               ' WHERE album_id = '.$iAlbumId;
        $iSongsCount = $oAlbumItem->oDb->getField($sSql);
        if (!$iSongsCount)
        {
            $oAlbumItem->delete($iAlbumId);
            return false;
        }
        return true;
    }

/** Searches entries accroding to search string and kind of search
 *
 * @param string $sValue : search string
 * @param string $sType  : kind of string (musician/album/song)
 * @return array : results of search | false on errors
 */
    function search($sValue='', $sType='')
    {
        $oSongItem = &$this->_oModule->getItem('Song');

        if( !$sValue || !$sType )
            return false;

        switch( $sType )
        {
            case "musician":
                $sSql = 'SELECT musician_id, musician_name, musician_is_featured'.
                        ' FROM '.App::getT('music_musician').
                        ' WHERE musician_name LIKE "%'.Database::escapeLike($sValue).'%"';
                return $oSongItem->oDb->getRows($sSql);
            break;

            case "album":
                $sSql = 'SELECT ma.album_id AS album_id,'.
                              ' ma.album_title AS album_title,'.
                              ' mm.musician_id AS musician_id,'.
                              ' mm.musician_name AS musician_name'.
                        ' FROM '.App::getT('music_album').' AS ma'.
                        ' INNER JOIN '.App::getT('music_musician').' AS mm USING (musician_id)'.
                        ' WHERE ma.album_title LIKE "%'.Database::escapeLike($sValue).'%"';
                //d($sSql, 1);
                return $oSongItem->oDb->getRows($sSql);
            break;

            case "song":
                $sSql = 'SELECT ms.song_id,'.
                              ' ms.song_title,'.
                              ' ms.song_is_featured,'.
                              ' mm.musician_id AS musician_id,'.
                              ' mm.musician_name AS musician_name'.
                        ' FROM '.App::getT('music_song').' AS ms'.
                        ' INNER JOIN '.App::getT('music_musician').' AS mm USING (musician_id)'.
                        ' WHERE ms.song_title LIKE "%'.Database::escapeLike($sValue).'%"';
                return $oSongItem->oDb->getRows($sSql);
            break;

            default:
                return false;
        }
    }

    /** Sets song to actual account song
     *
     * @param integer $iSongId
     * @param string $sUser
     * @return boolean
     */
    function setActualAccountMusic($iSongId, $sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */

        $iSongId = intval($iSongId);
        if (!$oSongItem->load($iSongId))
        {
            return false;
        }
        if (!$oSongItem->aData['song_is_approved'])
        {
            return false;
        }

        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!$oUser)
        {
            return false;
        }

        //fix 0019417:
        if($oUser->aData['id'] == $oSongItem->aData['user_id'])
        {
        	return false;
        }
        
        $oUser->aData['actual_song_id'] = $iSongId;
        $oUser->update(array('actual_song_id'));
        return true;
    }

    /** Get actual song_id for account
     *
     * @param string $sUser
     * @return integer
     */
    function getActualAccountMusic($sUser = '')
    {
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */

        if (!$sUser)
        {
            $oUser = $oSecurityService->getCurrentUser();
        }
        else
        {
            $oUser = $oAccountService->getByUsername($sUser);
        }
        if (!$oUser)
        {
            return 0;
        }
        return $oUser->aData['actual_song_id'];
    }

    /** Checks that song is actual
     *
     * @param integer $iSongId
     * @param string $sUser
     * @return boolean
     */
    function isSongActual($iSongId, $sUser = '')
    {
        $iSongId = intval($iSongId);
        $iActualSongId = $this->getActualAccountMusic($sUser);
        return ($iSongId == $iActualSongId);
    }

    /** Get newest songs and albums releases
     *
     * @param integer $iLimit
     * @return array
     */
    function getNewestReleases($iLimit)
    {
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */

        $iLimit = intval($iLimit);
        $sSql = '(SELECT ms.song_id AS id, ms.album_id AS album_id, ms.song_cdate AS cdate, ms.song_title AS title, mm.musician_name AS musician, mm.musician_id AS musician_id, "song" AS itype '.
                ' FROM '.App::getT('music_song').' AS ms '.
                ' LEFT JOIN '.App::getT('music_musician').' AS mm USING(musician_id) '.
                ' WHERE ms.album_id = 0 '.
                '   AND ms.song_is_approved = 1) '.
                ' UNION '.
                '(SELECT ma.album_id AS id, ma.album_id AS album_id, ma.album_cdate AS cdate, ma.album_title AS title, mm.musician_name AS musician, mm.musician_id AS musician_id, "album" AS itype '.
                ' FROM '.App::getT('music_album').' AS ma '.
                ' LEFT JOIN '.App::getT('music_musician').' AS mm USING(musician_id) '.
                ' LEFT JOIN '.App::getT('music_song').' AS ms ON(ms.album_id = ma.album_id AND ms.song_is_approved = 1) '.
                ' WHERE ma.album_is_approved = 1 AND ms.song_id IS NOT NULL ) '.
                ' ORDER BY cdate DESC '.
                ' LIMIT '.$iLimit;
        return $oSongItem->oDb->getRows($sSql);
    }

    /** Upload song on the server
     *
     * @param string $sSongFileName
     * @param array $aData
     * @param integer $iUserId
     * @return integer
     */
    function uploadSong($sSongFileName, $aData, $iUserId, $iMaxUploadSize = null)
    {
        $oSongItem = &$this->_oModule->getItem('Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */

        $oAccountService  = &App::getModuleService('Account', 'Account');
        $oSecurityService = &App::getModuleService('Account', 'Security');

        $iUserId = intval($iUserId);
        $iMusicianId = $this->addMusician($aData['musician_name']);
        $aData['genre_id'] = intval($aData['genre_id']);
        $oSongItem->aData['user_id']          = $iUserId;
        $oSongItem->aData['musician_id']      = $iMusicianId;
        $oSongItem->aData['genre_id']         = $aData['genre_id'];
        $oSongItem->aData['song_title']       = $aData['song_title'];
        $oSongItem->aData['song_cdate']       = Database::date();
        $oSongItem->aData['album_id']         = isset($aData['album_id']) ? $aData['album_id'] : 0;
        $oSongItem->aData['song_is_approved'] = App::getSetting('music_song_approving') ? 0 : 1;
        $iSongId = $oSongItem->insert();
        App::loadClass('file/File');

        $oFile = &new CFile();
        $sDestPath = App::getParam('music.path');

        $iMaxUploadSize = ($iMaxUploadSize ? $iMaxUploadSize : App::getParam('Mod_Music.max_song_size'));

        $oFile->aLimits['FILE_MAX_SIZE'] = $iMaxUploadSize;
        if ($oFile->upload($sSongFileName, $sDestPath, $iSongId, 'mp3'))
        {
            $oFile->loadInfo($sDestPath.$iSongId.'.mp3');
            $oFile->_checkLimits();
            /*
            if (!$this->_checkSongFormat($sDestPath.$iSongId.'.mp3'))
            {
                $this->addErrors(App::format('Mod_Music.error.wrong_format'));
            }
            */
        }
        $this->addErrors($oFile->getErrors());
        if (count($this->getErrors()))
        {
            $this->deleteSong($iSongId, false);
            return 0;
        }
        $oAccountService->changeUserInfo($oSecurityService->getCurrentUser(), 'music');
        return $iSongId;
    }

    /** Adding album to database and upload album label
     *
     * @param array $aAlbumData
     * @param integer $iUserId
     * @return integer
     */
    function addAlbum($aAlbumData, $iUserId)
    {
        $oAlbumItem = &$this->_oModule->getItem('Album');
        /* @var $oSongItem PhpFox_Mod_Music_ItemAlbum */

        $oAccountService  = &App::getModuleService('Account', 'Account');
        $oSecurityService = &App::getModuleService('Account', 'Security');
        
        $iUserId = intval($iUserId);
        $oAlbumItem->aData['album_title']       = $aAlbumData['album_title'];
        $oAlbumItem->aData['album_year']        = $aAlbumData['album_year'];
        $oAlbumItem->aData['album_cdate']       = Database::date();
        $oAlbumItem->aData['album_description'] = $aAlbumData['album_description'];
        $oAlbumItem->aData['musician_id']       = $this->addMusician($aAlbumData['musician_name']);
        $oAlbumItem->aData['genre_id']          = $aAlbumData['genre_id'];
        $oAlbumItem->aData['user_id']           = $iUserId;
        $oAlbumItem->aData['album_is_approved'] = App::getSetting('music_album_approving') ? 0 : 1;
        $iAlbumId = $oAlbumItem->insert();
        if (isset($_FILES['album_image']) && $_FILES['album_image']['size'])
        {
            if (!$this->_uploadAlbumPic('album_image', $iAlbumId))
            {
                $this->deleteAlbum($iAlbumId);
                return false;
            }
        }
        $oAccountService->changeUserInfo($oSecurityService->getCurrentUser(), 'music');
        return $iAlbumId;
    }

    /** Upload song to server
     *
     * @param string $sPicFile
     * @param integer $iAlbumId
     * @return boolean
     */
    function _uploadAlbumPic($sPicFile, $iAlbumId)
    {
        App::loadClass('file/Image');

        $sPicPath = App::getParam('music.album.pic.path');
        $oImage = &new file_Image();
        $oImage->aLimits['MAX_IMAGE_W'] = 0;
        $oImage->aLimits['MAX_IMAGE_H'] = 0;
        $oImage->aLimits['MIN_IMAGE_W'] = App::getParam('music.album.min_width');
        $oImage->aLimits['MIN_IMAGE_H'] = App::getParam('music.album.min_height');
        if ($oImage->upload($sPicFile, $sPicPath, $iAlbumId, 'jpg'))
        {
            $oImage->loadInfo($sPicPath.$iAlbumId.'.jpg');
            $oImage->_checkLimits();
            $iWidth = App::getParam('music.album.width');
            $iHeight = App::getParam('music.album.height');
            if (($oImage->nW > $iWidth) || ($oImage->nH > $iHeight))
            {
                $oImage->makeThumbnail($sPicPath.$iAlbumId.'.jpg', $iWidth, $iHeight);
            }
        }
        $this->addErrors($oImage->getErrors());
        if (count($this->getErrors()))
        {
            return false;
        }
        return true;
    }

    /** Reading mp3 file and comparing with mp3 format header
     *
     * @param string $sSongPath
     * @return boolean
     */
    function _checkSongFormat($sSongPath)
    {
        if (!file_exists($sSongPath))
        {
            return false;
        }
        $aMp3Headers = array
        (
            array(0x49, 0x44, 0x33, 0x03),
            array(0xFF, 0xFB),
        );
        $aSongData = array();
        $hF = fopen($sSongPath, 'r');
        for ($i = 0; $i < 4; $i++)
        {
            $aSongData[$i] = bin2hex(fread($hF, 1));
        }
        fclose($hF);
        foreach ($aMp3Headers as $aHeader)
        {
            $bEqual = true;
            for ($i = 0; $i < 4; $i++)
            {
                if (!isset($aHeader[$i]))
                {
                    break;
                }
                if (dechex($aHeader[$i]) != $aSongData[$i])
                {
                    $bEqual = false;
                    break;
                }
            }
            if ($bEqual)
            {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns Musicians list (cut off musicians with no songs)
     *
     * @param array $aCond Condition Array
     * @param string $sSort Sorting string
     * @return array
     */
    function getMusiciansList($aCond, $sSort)
    {
        $oAlbumItem = &$this->_oModule->getItem('Album');
        $sCond = '';

        foreach ($aCond as $sC)
        {
            $sCond .= $sC;
        }

        $sSql = '(SELECT mm.* '.
                ' FROM '.App::getT('music_song').' AS ms '.
                ' LEFT JOIN '.App::getT('music_musician').' AS mm USING(musician_id) '.
                ' WHERE ms.song_is_approved = 1' . ($sCond?(' AND '.$sCond):'') . ' ) '.
                ' UNION '.
                '(SELECT mm.* '.
                ' FROM '.App::getT('music_album').' AS ma '.
                ' LEFT JOIN '.App::getT('music_musician').' AS mm USING(musician_id) '.
                ' LEFT JOIN '.App::getT('music_song').' AS ms ON(ms.album_id = ma.album_id AND ms.song_is_approved = 1) '.
                ' WHERE ma.album_is_approved = 1 AND ms.song_id IS NOT NULL' . ($sCond?(' AND '.$sCond):'') . ' ) '.
                ' ORDER BY ' . $sSort;
        return $oAlbumItem->oDb->getRows($sSql);
    }

    /** Checks empty albums for last 1 month
     *
     *
     */
    function checkEmptyMusic()
    {
        $oAlbumItem = &$this->_oModule->getItem('Album');

        $sSql = ' SELECT ma.album_id, mm.musician_id FROM ' . App::getT('music_album') . ' AS ma ' .
                ' LEFT JOIN ' . App::getT('music_song') . ' AS ms USING ( album_id ) ' .
                ' LEFT JOIN ' . App::getT('music_musician') . ' AS mm ON (ma.musician_id = mm.musician_id) ' .
                ' WHERE ms.song_id IS NULL AND album_cdate < "' . date('Y-m-d h:i:s', strtotime('-1 months')) . '"';
        $aAlbums = $oAlbumItem->oDb->getRows($sSql);
        foreach ($aAlbums as $aId)
        {
            $oAlbumItem->delete($aId['album_id']);
            $this->checkMusician($aId['musician_id']);
        }
    }
    
	function getAccessForContent($sFile)
    {
    	$oCurUser = App::loadUser();
    	$iItemId = intval($sFile);
        if (!$iItemId)
        {
        	return false;
        }
        $oItem = $this->_oModule->getItem('Song');
        
        if ($oItem->load($iItemId))
        {
	        return ($oItem->aData['song_is_approved'] OR ($oItem->aData['user_id'] == $oCurUser->aData['id']) );
		}
		return false;
    }
}
?>